<?php

include_once "src/regexception/DBConnectionException.php";
include_once "src/regexception/DBException.php";
include_once "src/regexception/GeneralRegistryException.php";

class Connection {

    private $connectionId;

    function __construct () {
        try {
            //$this->connectionId = mysql_connect("localhost","root", "st4t3fuls4f3ty!!");
            $this->connectionId = mysql_connect("localhost","root", "root12345");
            if(!$this->connectionId) {
                throw new DBConnectionException("Unable to establish connection with the database server.");
            }
            if(!mysql_select_db("registrydb", $this->connectionId)) {
                throw new DBException("Unable to select the specified database.");
            }
        } catch(Exception $e) {
            throw new GeneralRegistryException();
        }
    }

    function __destruct () {
        //mysql_close($this->connectionId);
    }

    function execute ($query) {
        $result = mysql_query($query, $this->connectionId);
        if(!$result) {
            throw new DBException("Query execution failed. " .$query);
        }
        return $result;
    }

    function executeAsATransaction ($queries) {
        mysql_query("BEGIN", $this->connectionId);
        $results = array();
        for ($i = 0; $i < count($queries); $i++) {
            $results[$i] = mysql_query($queries[$i], $this->connectionId);
        }
        $temp = "";
        for ($i = 0; $i < count($results); $i++) {
            if (!$results[$i]) {
                mysql_query("ROLLBACK", $this->connectionId);
                throw new DBException("Query execution failed. ".$queries[$i]);
            }
        }
        mysql_query("COMMIT", $this->connectionId);
        return true;
    }

    function disconnect () {
        mysql_close($this->connectionId);
    }

    function getLastInsertId () {
        return mysql_insert_id($this->connectionId);
    }

}
?>
